package com.ayoka.utils;


import android.content.Context;
import android.media.AudioManager;

import com.jcp.baselibrary.utils.MyLogger;
import com.jcp.baselibrary.utils.UIUtils;

import java.util.Observable;

/**
 * 倒计时通知事件，上层界面可以订阅此事件
 */
public class AudioManagerEvent extends Observable {


    private volatile static AudioManagerEvent instance;

    private AudioManager.OnAudioFocusChangeListener mAudioFocusChangeListener = null;

    private AudioManagerEvent() {
        mAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
            @Override
            public void onAudioFocusChange(int focusChange) {
                MyLogger.i("AudioManagerEvent", "focusChange = " + focusChange);
                setChanged();
                notifyObservers(focusChange);
            }
        };
    }

    public static AudioManagerEvent getInstance() {
        if (instance == null) {
            synchronized (AudioManagerEvent.class) {
                if (instance == null) {
                    instance = new AudioManagerEvent();
                }
            }
        }
        return instance;
    }

    public void requestAudioFocus() {
        AudioManager audioManager = (AudioManager) UIUtils.getContext().getSystemService(Context.AUDIO_SERVICE);
        int result = audioManager.requestAudioFocus(mAudioFocusChangeListener,
                AudioManager.STREAM_SYSTEM, AudioManager.AUDIOFOCUS_GAIN);
        if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            MyLogger.i("AudioManagerEvent", "request audio focus fail. " + result);
        }
    }

    public void abandonAudioFocus() {
        AudioManager audioManager = (AudioManager) UIUtils.getContext().getSystemService(Context.AUDIO_SERVICE);
        audioManager.abandonAudioFocus(mAudioFocusChangeListener);
    }

    /**
     * 清理监听
     */
    public void clear() {
        instance = null;
        mAudioFocusChangeListener = null;
    }
}
